<template>
  <div ref="bookWrap">
    <h6>{{ current.title }}</h6>
    <pre class="content-wrap">{{ current.content }}</pre>
  </div>
</template>

<script lang="ts" setup>
import { ref, onMounted } from 'vue'

export interface Chapter {
  title?: string;
  content?: string;
}
const contents = ref([])
const current = ref<Chapter>({})
const chapterIndex = ref(0)
const bookWrap = ref()
const emits = defineEmits(['toogleNav'])

const readTxt = (url: string) => {
  const xhr = new XMLHttpRequest()
  console.log(xhr)
  xhr.open('GET', url, false)
  xhr.overrideMimeType('text/html;charset=gb2312')
  xhr.addEventListener('loadend', (e) => {
    const responseText = (e.target as any).responseText
    const contentArr = responseText.split(/###.+###/).splice(1)
    const titleArr = responseText.match(/###.+###/g)
    console.log(contentArr)
    console.log(titleArr)
    contents.value = contentArr.map((item: string, index: number) => ({
      title: titleArr[index].replace(/#/g, ''),
      content: item.replace('\n\n', '')
    }))
    console.log(contents.value)
    current.value = contents.value[chapterIndex.value]
  })
  xhr.send()
  // const reader = new window.FileReader()
  // reader.onload = (e) => {
  //   content.value = String(e.target.result)
  //   console.log(content.value)
  // }
  // reader.readAsText(url, 'utf-8')
}

const initEvent = () => {
  let touchstartX = 0
  let touchStartTime = 0
  const prevPage = () => {
    console.log('prevPage')
    //rendition && rendition.prev()
    chapterIndex.value = chapterIndex.value - 1
    if (chapterIndex.value < 0) {
      chapterIndex.value = 0
    } else {
      current.value = contents.value[chapterIndex.value]
    }
  }
  const nextPage = () => {
    //rendition && rendition.next()
    console.log('nextPage')
    chapterIndex.value = chapterIndex.value + 1
    current.value = contents.value[chapterIndex.value]
  }
  const toogleTitleAndMenu = () => {
    console.log('toogleNav')
    emits('toogleNav')
  }
  bookWrap.value.addEventListener('touchstart', (event: any) => {
    // event.preventDefault()
    // event.stopPropagation()
    touchstartX = event.changedTouches[0].clientX
    touchStartTime = event.timeStamp
  })

  bookWrap.value.addEventListener('touchend', (event: any) => {
    // event.preventDefault()
    // event.stopPropagation()
    const offsetX = event.changedTouches[0].clientX - touchstartX
    const time = event.timeStamp - touchStartTime
    console.log(offsetX, time)
    if (time < 500 && offsetX > 40) {
      prevPage()
    } else if (time < 500 && offsetX < -40) {
      nextPage()
    } else {
      toogleTitleAndMenu()
    }
  })
}
readTxt('./故障乌托邦.txt')

onMounted(() => {
  initEvent()
})
</script>

<style scoped>
.content-wrap {
  width: 100vw;
  white-space: pre-wrap;
  padding: 8px;
  font-size: 20px;
  font-family: '微软雅黑';
}

h6 {
  font-size: 20px;
  font-weight: 600;
  text-align: center;
  padding-top: 30px;
}
</style>